/*
 * @Descripttion: 
 * @version: 
 * @Author: Indolphin
 * @Date: 2021-02-28 21:12:46
 * @LastEditors: Indolphin
 * @LastEditTime: 2021-03-14 14:51:28
 */
/**
 * redux action creator
 * 
 * @author Indolphin
 */
import { message } from 'antd';
import { Dispatch } from 'redux';
import { UpdateUserActionType, UPDATE_USER } from './types';
import { login, logout } from '../service/index';
import { LoginResponse } from '../interface';
import storage from '../utils/storeage';

/**
 * 更新用户信息
 * 
 * @param username 用户名
 * @returns 
 */
export const updateUser = (username: string): UpdateUserActionType => ({
    type: UPDATE_USER,
    payload: {
        username
    }
})

/**
 * 用户登录，异步
 * 
 * @param username 用户名
 * @param password 密码
 * @param rememberme 记住登录
 * @returns 
 */
export const loginUser = ({ username, password, rememberme }: any): any => {
    
    return (dispatch: Dispatch<UpdateUserActionType>) => {
        login({
            username,
            password,
            rememberme
        }).then((response: any) => {
            console.log('loign response = ', response);
            const { access_token } = response;
            // 存储用户token
            storage.saveAccessToken(access_token);
            // 存储用户名
            storage.saveUserInfo({
                username
            });
            dispatch({
                type: UPDATE_USER,
                payload: {
                    username
                }
            });
        }).catch(error => {
            console.log("error = ", error);
            message.error(error);
        })
    }
}


/**
 * 用户注销，异步
 * 
 * @param {*}
 * @return {*}
 */
export const logoutUser = (): any => {
    return (dispatch: Dispatch<UpdateUserActionType>) => {
        logout().then(response => {
            storage.saveAccessToken('');
            storage.saveUserInfo({ username: '' });
            dispatch({
                type: UPDATE_USER,
                payload: {
                    username: ''
                }
            });
        }).catch(error => {
            message.error(error);
        });
    };
}